package com.zhentao.service;

import com.zhentao.websocket.pojo.ChatGroupMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 群聊消息服务类
 */
@Service
public class ChatGroupMessageService {

    private static final Logger log = LoggerFactory.getLogger(ChatGroupMessageService.class);

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 保存群聊消息
     */
    public ChatGroupMessage saveMessage(ChatGroupMessage message) {
        try {
            // 验证消息内容
            if (message == null) {
                throw new IllegalArgumentException("消息不能为空");
            }
            
            if (message.getGroupId() == null) {
                throw new IllegalArgumentException("群组ID不能为空");
            }
            
            if (message.getFromName() == null || message.getFromName().trim().isEmpty()) {
                throw new IllegalArgumentException("发送者不能为空");
            }
            
            if (message.getMessage() == null || message.getMessage().trim().isEmpty()) {
                throw new IllegalArgumentException("消息内容不能为空");
            }
            
            // 清理和标准化数据
            message.setFromName(message.getFromName().trim());
            message.setMessage(message.getMessage().trim());
            
            // 设置默认值
            if (message.getTimestamp() == null) {
                message.setTimestamp(LocalDateTime.now());
            }
            
            if (message.getMessageType() == null || message.getMessageType().trim().isEmpty()) {
                message.setMessageType("text");
            }
            
            // 保存到MongoDB
            ChatGroupMessage saved = mongoTemplate.save(message);
            log.info("群聊消息保存成功: 群组ID={}, 发送者={}, ID={}", 
                message.getGroupId(), message.getFromName(), saved.getId());
            
            return saved;
            
        } catch (Exception e) {
            log.error("保存群聊消息失败", e);
            throw new RuntimeException("保存群聊消息失败: " + e.getMessage(), e);
        }
    }
    
    /**
     * 批量保存群聊消息
     */
    public List<ChatGroupMessage> saveMessages(List<ChatGroupMessage> messages) {
        try {
            if (messages == null || messages.isEmpty()) {
                return new ArrayList<>();
            }
            
            // 验证所有消息
            for (ChatGroupMessage message : messages) {
                if (message.getGroupId() == null || message.getFromName() == null || message.getMessage() == null) {
                    throw new IllegalArgumentException("批量保存中包含无效消息");
                }
                
                // 设置默认值
                if (message.getTimestamp() == null) {
                    message.setTimestamp(LocalDateTime.now());
                }
                if (message.getMessageType() == null) {
                    message.setMessageType("text");
                }
            }
            
            Collection<ChatGroupMessage> saved = mongoTemplate.insertAll(messages);
            List<ChatGroupMessage> result = new ArrayList<>(saved);
            log.info("批量保存群聊消息成功，数量: {}", result.size());
            return result;
            
        } catch (Exception e) {
            log.error("批量保存群聊消息失败", e);
            throw new RuntimeException("批量保存群聊消息失败: " + e.getMessage(), e);
        }
    }
    
    /**
     * 获取群聊历史消息
     */
    public List<ChatGroupMessage> getGroupChatHistory(Long groupId, int page, int size) {
        try {
            if (groupId == null) {
                throw new IllegalArgumentException("群组ID不能为空");
            }
            
            Query query = new Query();
            query.addCriteria(Criteria.where("groupId").is(groupId)
                    .and("isDeleted").is(false));
            
            // 按时间倒序排列，然后分页
            query.with(Sort.by(Sort.Direction.DESC, "timestamp"));
            query.skip((long) page * size);
            query.limit(size);
            
            List<ChatGroupMessage> messages = mongoTemplate.find(query, ChatGroupMessage.class);
            
            // 反转列表，使最新消息在底部
            List<ChatGroupMessage> sortedMessages = messages.stream()
                    .sorted((m1, m2) -> m1.getTimestamp().compareTo(m2.getTimestamp()))
                    .collect(Collectors.toList());
            
            log.info("获取群聊记录: 群组ID={}, 数量={}, 页码={}, 大小={}", 
                groupId, sortedMessages.size(), page, size);
            return sortedMessages;
            
        } catch (Exception e) {
            log.error("获取群聊记录失败: 群组ID={}", groupId, e);
            throw new RuntimeException("获取群聊记录失败: " + e.getMessage(), e);
        }
    }
    
    /**
     * 获取群聊最新消息
     */
    public ChatGroupMessage getLatestMessage(Long groupId) {
        try {
            if (groupId == null) {
                return null;
            }
            
            Query query = new Query();
            query.addCriteria(Criteria.where("groupId").is(groupId)
                    .and("isDeleted").is(false));
            query.with(Sort.by(Sort.Direction.DESC, "timestamp"));
            query.limit(1);
            
            return mongoTemplate.findOne(query, ChatGroupMessage.class);
            
        } catch (Exception e) {
            log.error("获取群聊最新消息失败: 群组ID={}", groupId, e);
            return null;
        }
    }
    
    /**
     * 删除群聊消息（软删除）
     */
    public boolean deleteMessage(String messageId) {
        try {
            if (messageId == null || messageId.trim().isEmpty()) {
                return false;
            }
            
            ChatGroupMessage message = mongoTemplate.findById(messageId, ChatGroupMessage.class);
            if (message != null) {
                message.setDeleted(true);
                mongoTemplate.save(message);
                log.info("群聊消息删除成功: ID={}", messageId);
                return true;
            }
            
            return false;
            
        } catch (Exception e) {
            log.error("删除群聊消息失败: ID={}", messageId, e);
            return false;
        }
    }
    
    /**
     * 获取群聊消息总数
     */
    public long getMessageCount(Long groupId) {
        try {
            if (groupId == null) {
                return 0;
            }
            
            Query query = new Query();
            query.addCriteria(Criteria.where("groupId").is(groupId)
                    .and("isDeleted").is(false));
            
            return mongoTemplate.count(query, ChatGroupMessage.class);
            
        } catch (Exception e) {
            log.error("获取群聊消息总数失败: 群组ID={}", groupId, e);
            return 0;
        }
    }
}
